<template>
  <div class="name-div">
    <a-input
      v-model:value="nodeName"
      placeholder="请输入"
      :maxlength="32"
      @change="nameChange"
    />
    <CheckOutlined class="button-class" @click="confirm" />
    <CloseOutlined class="button-class" @click="cancel" />
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { CheckOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

/**
 * 外部参数
 */
let props = defineProps({
  node: { type: Object, default: () => {} },
  itemData: { type: Object, default: () => {} },
})
let emit = defineEmits(['nodeChange'])
let nodeName = ref('')
let allowChange = true
nodeName.value = props.node.title
// 前端搜索校验名称是否重复
function nameChange() {
  let parentId = props.node?.parentId
  let currntParent = []
  if (props.itemData.id == parentId) {
    // 根节点
    currntParent = props.itemData
  } else {
    // 普通节点
    currntParent = getNodeById(props.itemData.children, parentId)
  }
  allowChange = true
  currntParent.children.forEach(item => {
    if (item.title == nodeName.value) {
      message.warning('该名称已存在，请重新输入。')
      allowChange = false
      return
    }
  })
}
function confirm() {
  if (allowChange) {
    // 名称不重复
    // todo  存入后端 + update刷新
    if (props.node.id) {
      // edit
      emit('nodeChange', {
        event: 'edit',
        node: props.node,
        name: nodeName.value,
      })
    } else {
      // add
      emit('nodeChange', {
        event: 'add',
        node: props.node,
        name: nodeName.value,
      })
    }
  }
}
function cancel() {
  if (props.node.id) {
    emit('nodeChange', {
      event: 'cancel',
      node: props.node,
      key: 'edit',
    })
  } else {
    emit('nodeChange', {
      event: 'cancel',
      node: props.node,
      key: 'add',
    })
  }
}
/**
 * 树节点功能操作
 */
// 根据节点id在树上查找节点
function getNodeById(data, id) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === id) {
      return data[i]
    }
    if (data[i].children) {
      const foundNode = getNodeById(data[i].children, id)
      if (foundNode) {
        return foundNode
      }
    }
  }
  return null
}
</script>
<style scoped lang="less">
.name-div {
  height: 25px;
  padding: 5px;
  display: flex;
  justify-content: flex-end;
}
.button-class {
  margin-left: 10px;
  color: #0086ff;
}
</style>
